<template>
  <el-dialog v-model="dialogVisible" title="编辑服务" width="800">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="100"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="服务名称" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="图片" prop="pic">
        <el-upload
          v-model:file-list="fileList"
          action="https://www.jqw2019.com/admin/api/v1/files"
          list-type="picture-card"
          :headers="headers"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :on-success="handleSuccess"
          :limit="1"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <!-- <el-input v-model="ruleForm.name" /> -->
        <el-input-number
          v-model="ruleForm.price"
          :precision="2"
          :controls="false"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="服务介绍" prop="description">
        <el-input v-model="ruleForm.description" type="textarea" />
      </el-form-item>
      <el-form-item label="服务范围" prop="serviceScope">
        <el-input v-model="ruleForm.serviceScope" type="textarea" />
      </el-form-item>
      <el-form-item label="服务保障" prop="serviceGuarantee">
        <el-input v-model="ruleForm.serviceGuarantee" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisibleImg">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import serviceInfoAPI from "@/api/serviceinfo";

const emit = defineEmits(["updatePages"]);
const headers = { Authorization: localStorage.getItem(TOKEN_KEY) };
const typeId = ref();

const dialogVisible = ref(false);
const init = (id, value) => {
  console.log(id, value);
  typeId.value = id;
  if (value) {
    serviceInfoAPI
      .showServiceInfo(value)
      .then((res) => {
        for (let key in res) {
          ruleForm[key] = res[key];
        }
        if (res.pic) {
          fileList.value[0] = {
            url: res.pic,
          };
        }
      })
      .catch((err) => {});
    dialogVisible.value = true;
  } else {
    dialogVisible.value = true;
  }
};
defineExpose({
  init,
});
const handleClose = () => {
  // ElMessageBox.confirm("Are you sure to close this dialog?")
  //   .then(() => {})
  //   .catch(() => {});
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  fileList.value = [];
};

//表单
const ruleForm = reactive({});
const rules = reactive({
  title: [
    {
      required: true,
      message: "请输入服务名称",
      trigger: "blur",
    },
  ],
  price: [
    {
      required: true,
      message: "请输入价格",
      trigger: "blur",
    },
  ],
});
const ruleFormRef = ref();
const handleSubmit = async (formEl) => {
  console.log(formEl, "formEl");
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let params = {
        ...ruleForm,
        typeId: typeId.value,
      };
      if (fileList.value.length > 0) {
        params.pic = fileList.value[0].url;
      }
      let request = ruleForm.id
        ? serviceInfoAPI.editServiceInfo
        : serviceInfoAPI.addServiceInfo;
      request(params)
        .then((res) => {
          dialogVisible.value = false;
          emit("updatePages", typeId.value);
          ruleFormRef.value.resetFields();
          fileList.value = [];
        })
        .catch((err) => {});
    } else {
      console.log("error submit!", fields);
    }
  });
};
//上传图片

const fileList = ref([]);

const dialogImageUrl = ref("");
const dialogVisibleImg = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisibleImg.value = true;
};

const handleSuccess = (response, uploadFile, uploadFiles) => {
  uploadFiles.find((item) => item.name == uploadFile.name).url =
    uploadFile.response.data.url;
};
const handleExceed = () => {
  ElMessage({
    message: "最多选择一张图片",
    type: "warning",
  });
};
</script>
<style lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
